<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="导入表结构" :helpMessage="['从数据库导入表结构']" width="1000px" @ok="handleSubmit">
    <BasicTable @register="registerTable" :rowSelection="{ type: 'checkbox', selectedRowKeys: checkedKeys, onChange: onSelectChange }" size="small"> </BasicTable>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicTable, useTable } from '/@/components/Table';
  import * as _API from '../../api';
  import { getDbFormConfig, getDBTables } from '../../config';

  export default defineComponent({
    components: { BasicModal, BasicForm, BasicTable },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const checkedKeys = ref<Array<string | number>>([]);
      const { createMessage } = useMessage();
      const { warning } = createMessage;
      const [registerTable, { getSelectRowKeys, getForm, reload }] = useTable({
        api: _API.getDBPageList,
        afterFetch(info) {
          checkedKeys.value = [];
          return info;
        },
        columns: getDBTables(),
        formConfig: getDbFormConfig(),
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        showIndexColumn: true,
        canResize: false,
        clickToRowSelect: false,
        rowKey: 'tableName',
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async () => {
        setModalProps({
          confirmLoading: false,
        });
        await reload();
      });

      //
      async function handleSubmit() {
        try {
          let tables: string[] = getSelectRowKeys();
          if (tables.length == 0) {
            warning('至少选中一条数据');
            return;
          }
          setModalProps({ confirmLoading: true });
          const group = getForm().getFieldsValue()['group'];
          await _API.importAPI({ group: group, tables: tables }).then(() => {
            closeModal();
          });
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      function onSelectChange(selectedRowKeys: (string | number)[]) {
        checkedKeys.value = selectedRowKeys;
      }

      return {
        registerModal,
        registerTable,
        checkedKeys,
        handleSubmit,
        onSelectChange,
      };
    },
  });
</script>
